<!--
 * @Descripttion: 
 * @version: 
 * @Author: ybac
 * @Date: 2022-08-08 15:57:32
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2022-08-29 14:24:02
-->
<template>
  <div class="wraper-box">
    <a-modal v-model="visible" title="批次生产记录" on-cancel="handleCancel" :width="1000" centered>
      <template slot="footer">
        <span style="float: left; line-height: 32px">共{{ dataSource.length }}条</span>
        <a-pagination
          :total="total"
          v-model="current"
          :page-size-options="pageSizeOptions"
          :page-size="pageSize"
          @change="onChangePage"
          @showSizeChange="onChangePage"
          show-quick-jumper
          show-size-changer
        />
      </template>
      <a-card :bordered="false" size="small" style="height: calc(100vh - 316px)">
        <div class="topBox">
          <div>
            <a-button @click="handleShowFilter" icon="filter" style="margin-right: 10px">
              筛选 <span style="color: #1890ff; margin-left: 5px">{{ ' ' + filteredNums }}</span></a-button
            >
            <a-button @click="showColumn" icon="unordered-list" style="margin-right: 10px"> 设置列 </a-button>
          </div>
          <div class="right-btn">
            <PubExport
              exportUrl="/mess/messProductBatch/exportQueryProduceRecordXls"
              :columns="columns"
              :propForm="propForm()"
              :selectedRows="[]"
              :sortForm="sortForm"
              :fullName="fullName"
              :action="'downFile'"
            />
          </div>
        </div>
        <a-table
          row-key="id"
          :key="tableKey"
          :columns="columns"
          :data-source="dataSource"
          :pagination="false"
          :scroll="{ x: scrollX, y: 'calc(100vh - 412px)' }"
          @change="tableChange"
          :loading="loadingTable"
          :components="drag(columns, Entity, 'BATCH')"
        >
          <!-- 选择搜索 -->
          <div slot="selectDropdown" slot-scope="{ column }" class="searchWorkOreder">
            <a-select
              mode="multiple"
              allowClear
              placeholder="请选择"
              style="width: 200px"
              v-model="filterForm[column.searchKey]"
              @change="(v) => changeSelect(v, column.selectKey)"
            >
              <a-select-option
                v-for="(item, index) in getList(column.list)"
                :key="index"
                :value="item[column.selectValue]"
                >{{ item[column.selectText] }}</a-select-option
              >
            </a-select>
            <a-button type="primary" style="width: 80px; margin-left: 20px; display: block" @click="handleSearch">
              搜索
            </a-button>
          </div>
          <!-- 日期搜索 -->
          <div slot="datePicker" slot-scope="{ column }" class="searchWorkOreder">
            <a-range-picker
              style="width: 188px"
              v-model="dateForm[column.selectValue]"
              format="YYYY-MM-DD"
              :placeholder="['开始时间', '结束时间']"
              @change="(v) => onOk(v, column.selectValue)"
            />
            <a-button type="primary" style="width: 80px; margin-left: 20px; display: block" @click="handleSearch">
              搜索
            </a-button>
          </div>
          <a-icon
            slot="selectIcon"
            slot-scope="filtered"
            type="filter"
            :style="{ color: filtered ? '#108ee9' : undefined }"
          />
        </a-table>
        <SetColumn
          columnName="设置列"
          ref="SetColumn"
          v-if="showSetColumn"
          @sureBtn="sureBtn"
          @cancelBtn="showSetColumn = false"
        />
      </a-card>
      <a-drawer
        placement="right"
        :closable="false"
        :visible="showFilter"
        v-if="showFilter"
        :get-container="false"
        :wrap-style="{ position: 'absolute' }"
        @close="closeFilter"
        :width="350"
      >
        <div class="filter-body">
          <div slot="title" class="uni-card filter-tit">
            筛选 <span class="filter-num">{{ filteredNums }}</span>
          </div>
          <div class="uni-card" v-if="filteredNums > 0" style="background: #fff">
            <div v-for="(item, i) in filteredList" :key="i" v-show="item.text" class="tag-wrap">
              <span class="filter-tag" @click="delFiltered(item.key)">
                <span class="tag-text">{{ `${item.title}：${item.text}` }}</span>
                <a-icon type="close" style="float: right" />
              </span>
            </div>
          </div>
          <div style="overflow-y: scroll; flex: 1; padding: 0">
            <div class="uni-card" style="background: #fff">
              <a-form-model ref="ruleForm" layout="vertical" :model="filterForm">
                <a-form-model-item label="操作时间">
                  <a-range-picker
                    style="width: 100%"
                    v-model="dateForm['operateTime']"
                    format="YYYY-MM-DD"
                    :placeholder="['开始时间', '结束时间']"
                    @change="(v) => onOk(v, ['operateTime'])"
                  />
                </a-form-model-item>
                <a-form-model-item label="操作类型">
                  <a-select
                    mode="multiple"
                    @change="(v) => changeSelect(v, 'operateType')"
                    allowClear
                    placeholder="请选择"
                    style="width: 100%"
                    v-model="filterForm['operateType']"
                  >
                    <a-select-option v-for="(item, i) in typeList" :key="i" :value="item.value">{{
                      item.text
                    }}</a-select-option>
                  </a-select>
                </a-form-model-item>
                <a-form-model-item label="工序">
                  <a-select
                    mode="multiple"
                    @change="(v) => changeSelect(v, 'taskId')"
                    allowClear
                    placeholder="请选择"
                    style="width: 100%"
                    v-model="filterForm['taskId']"
                  >
                    <a-select-option v-for="(item, i) in taskList" :key="i" :value="item.id">{{
                      item.processName
                    }}</a-select-option>
                  </a-select>
                </a-form-model-item>
                <a-form-model-item label="设备">
                  <a-select
                    mode="multiple"
                    @change="(v) => changeSelect(v, 'deviceId')"
                    allowClear
                    placeholder="请选择"
                    style="width: 100%"
                    v-model="filterForm['deviceId']"
                  >
                    <a-select-option v-for="(item, i) in deviceList" :key="i" :value="item.value">{{
                      item.text
                    }}</a-select-option>
                  </a-select>
                </a-form-model-item>
                <a-form-model-item label="操作人">
                  <a-select
                    mode="multiple"
                    @change="(v) => changeSelect(v, 'operatorId')"
                    allowClear
                    placeholder="请选择"
                    style="width: 100%"
                    v-model="filterForm['operatorId']"
                  >
                    <a-select-option v-for="(item, i) in operatorList" :key="i" :value="item.value">{{
                      item.text
                    }}</a-select-option>
                  </a-select>
                </a-form-model-item>
                <a-form-model-item label="班组">
                  <a-select
                    mode="multiple"
                    @change="(v) => changeSelect(v, 'teamGroupId')"
                    allowClear
                    placeholder="请选择"
                    style="width: 100%"
                    v-model="filterForm['teamGroupId']"
                  >
                    <a-select-option v-for="(item, i) in teamList" :key="i" :value="item.value">{{
                      item.text
                    }}</a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-form-model>
            </div>
          </div>
          <div class="footer-submit">
            <a-button class="margin-btn" @click="resetFilter">重置</a-button>
            <a-button type="primary" @click="handleFilter">确定</a-button>
          </div>
        </div>
      </a-drawer>
    </a-modal>
  </div>
</template>
<script>
import SetColumn from '@/pubComponent/SetColumn.vue'
import { getNewColumns } from '@/utils/util'
import tableDragResize from '@/mixins/tableDragResize'
import PubExport from '@/components/pubBtn/PubExport.vue'
import moment from 'moment'
import {
  queryProduceRecord,
  getTaskOptionList,
  getDeviceListByBatchId,
  getOperatorListByBatchId,
  getTeamGroupByBatchId,
} from '@/api/productOrder'
const columnsValue = [
  {
    title: '操作时间',
    dataIndex: 'operateTime',
    sorter: true,
    searchKey: 'operateTime',
    width: 180,
    ellipsis: true,
    // scopedSlots: {
    //   filterDropdown: 'datePicker',
    //   filterIcon: 'selectIcon',
    //   customRender: 'operateTime',
    // },
  },
  {
    title: '操作类型',
    dataIndex: 'operateType',
    searchKey: 'operateType',
    list: 'typeList',
    selectValue: 'value',
    selectText: 'text',
    width: 100,
    ellipsis: true,
    scopedSlots: {
      filterDropdown: 'selectDropdown',
      filterIcon: 'selectIcon',
      customRender: 'operateType',
    },
  },
  {
    title: '工序',
    dataIndex: 'taskName',
    searchKey: 'taskId',
    list: 'taskList',
    selectValue: 'id',
    selectText: 'processName',
    width: 150,
    ellipsis: true,
    scopedSlots: {
      filterDropdown: 'selectDropdown',
      filterIcon: 'selectIcon',
      customRender: 'taskId',
    },
  },
  {
    title: '摘要',
    dataIndex: 'summary',
    width: 230,
    ellipsis: true,
  },
  {
    title: '设备',
    dataIndex: 'deviceName',
    searchKey: 'deviceId',
    list: 'deviceList',
    selectValue: 'value',
    selectText: 'text',
    width: 180,
    ellipsis: true,
    scopedSlots: {
      filterDropdown: 'selectDropdown',
      filterIcon: 'selectIcon',
      customRender: 'deviceName',
    },
  },
  {
    title: '操作人',
    dataIndex: 'operatorName',
    searchKey: 'operatorId',
    list: 'operatorList',
    selectValue: 'value',
    selectText: 'text',
    width: 120,
    ellipsis: true,
    scopedSlots: {
      filterDropdown: 'selectDropdown',
      filterIcon: 'selectIcon',
      customRender: 'operatorId',
    },
  },
  {
    title: '班组',
    dataIndex: 'teamGroupName',
    searchKey: 'teamGroupId',
    list: 'teamList',
    selectValue: 'value',
    selectText: 'text',
    width: 180,
    ellipsis: true,
    scopedSlots: {
      filterDropdown: 'selectDropdown',
      filterIcon: 'selectIcon',
      customRender: 'teamGroupName',
    },
  },
]
export default {
  mixins: [tableDragResize],
  components: { SetColumn, PubExport },
  data() {
    return {
      visible: false,
      loadingTable: false,
      dataSource: [],
      columns: [
        {
          title: '操作时间',
          dataIndex: 'operateTime',
          sorter: true,
          searchKey: 'operateTime',
          width: 180,
          ellipsis: true,
          // scopedSlots: {
          //   filterDropdown: 'datePicker',
          //   filterIcon: 'selectIcon',
          //   customRender: 'operateTime',
          // },
        },
        {
          title: '操作类型',
          dataIndex: 'operateType',
          searchKey: 'operateType',
          list: 'typeList',
          selectValue: 'value',
          selectText: 'text',
          width: 100,
          ellipsis: true,
          scopedSlots: {
            filterDropdown: 'selectDropdown',
            filterIcon: 'selectIcon',
            customRender: 'operateType',
          },
        },
        {
          title: '工序',
          dataIndex: 'taskName',
          searchKey: 'taskId',
          list: 'taskList',
          selectValue: 'id',
          selectText: 'processName',
          width: 150,
          ellipsis: true,
          scopedSlots: {
            filterDropdown: 'selectDropdown',
            filterIcon: 'selectIcon',
            customRender: 'taskId',
          },
        },
        {
          title: '摘要',
          dataIndex: 'summary',
          width: 230,
          ellipsis: true,
        },
        {
          title: '设备',
          dataIndex: 'deviceName',
          searchKey: 'deviceId',
          list: 'deviceList',
          selectValue: 'value',
          selectText: 'text',
          width: 180,
          ellipsis: true,
          scopedSlots: {
            filterDropdown: 'selectDropdown',
            filterIcon: 'selectIcon',
            customRender: 'deviceName',
          },
        },
        {
          title: '操作人',
          dataIndex: 'operatorName',
          searchKey: 'operatorId',
          list: 'operatorList',
          selectValue: 'value',
          selectText: 'text',
          width: 120,
          ellipsis: true,
          scopedSlots: {
            filterDropdown: 'selectDropdown',
            filterIcon: 'selectIcon',
            customRender: 'operatorId',
          },
        },
        {
          title: '班组',
          dataIndex: 'teamGroupName',
          searchKey: 'teamGroupId',
          list: 'teamList',
          selectValue: 'value',
          selectText: 'text',
          width: 180,
          ellipsis: true,
          scopedSlots: {
            filterDropdown: 'selectDropdown',
            filterIcon: 'selectIcon',
            customRender: 'teamGroupName',
          },
        },
      ],
      sortForm: {
        sortType: '',
        sortColumn: '',
      },
      filterForm: {
        operateTimeBegin: '',
        operateTimeEnd: '',
        operateType: undefined,
        taskId: undefined,
        deviceId: undefined,
        operatorId: undefined,
        teamGroupId: undefined,
      },
      filteredFormLable: {
        operateTimeBegin: '操作时间',
        operateType: '操作类型',
        taskId: '工序',
        deviceId: '设备',
        operatorId: '操作人',
        teamGroupId: '班组',
      },
      // 分页begin
      current: 1,
      total: 0,
      pageSize: 30,
      pageSizeOptions: ['10', '20', '30', '40', '50'],
      // 分页end
      requestId: '',
      tableKey: 1.9,
      showFilter: false,
      showSetColumn: false,
      batchInfo: {},
      dateForm: {},
      taskList: [],
      typeList: [
        { text: '生成', value: '生成' },
        { text: '生产报工', value: '生产报工' },
        { text: '质检报工', value: '质检报工' },
        { text: '合格品入库', value: '合格品入库' },
      ],
      deviceList: [],
      operatorList: [],
      teamList: [],
      fullName: '',
      Entity: '',
    }
  },
  computed: {
    scrollX() {
      let xnum = 0
      for (let item of this.columns) {
        xnum += Number(item.width) || 0
      }
      return xnum
    },
    filteredNums() {
      let nums = 0
      for (let key in this.filterForm) {
        if (this.filterForm[key] && this.filterForm[key].length > 0) {
          nums += 1
          if (key == 'operateTimeBegin') {
            nums -= 1
          }
        }
      }
      return nums
    },
    filteredList() {
      let list = []
      for (let key in this.filterForm) {
        if (key == 'operateType' && this.filterForm[key] && this.filterForm[key].length > 0) {
          let arr = this.filterForm[key]
          let texts = []
          for (let i = 0; i < this.typeList.length; i++) {
            const e = this.typeList[i]
            for (let j = 0; j < arr.length; j++) {
              const k = arr[j]
              if (k == e.value) {
                texts.push(e.text)
              }
            }
          }
          list.push({
            title: this.filteredFormLable[key],
            text: texts.join(','),
            key,
          })
        } else if (key == 'taskId' && this.filterForm[key] && this.filterForm[key].length > 0) {
          let arr = this.filterForm[key]
          let texts = []
          for (let i = 0; i < this.taskList.length; i++) {
            const e = this.taskList[i]
            for (let j = 0; j < arr.length; j++) {
              const k = arr[j]
              if (k == e.id) {
                texts.push(e.processName)
              }
            }
          }
          list.push({
            title: this.filteredFormLable[key],
            text: texts.join(','),
            key,
          })
        } else if (key == 'deviceId' && this.filterForm[key] && this.filterForm[key].length > 0) {
          let arr = this.filterForm[key]
          let texts = []
          for (let i = 0; i < this.deviceList.length; i++) {
            const e = this.deviceList[i]
            for (let j = 0; j < arr.length; j++) {
              const k = arr[j]
              if (k == e.value) {
                texts.push(e.text)
              }
            }
          }
          list.push({
            title: this.filteredFormLable[key],
            text: texts.join(','),
            key,
          })
        } else if (key == 'operatorId' && this.filterForm[key] && this.filterForm[key].length > 0) {
          let arr = this.filterForm[key]
          let texts = []
          for (let i = 0; i < this.operatorList.length; i++) {
            const e = this.operatorList[i]
            for (let j = 0; j < arr.length; j++) {
              const k = arr[j]
              if (k == e.value) {
                texts.push(e.text)
              }
            }
          }
          list.push({
            title: this.filteredFormLable[key],
            text: texts.join(','),
            key,
          })
        } else if (key == 'teamGroupId' && this.filterForm[key] && this.filterForm[key].length > 0) {
          let arr = this.filterForm[key]
          let texts = []
          for (let i = 0; i < this.teamList.length; i++) {
            const e = this.teamList[i]
            for (let j = 0; j < arr.length; j++) {
              const k = arr[j]
              if (k == e.value) {
                texts.push(e.text)
              }
            }
          }
          list.push({
            title: this.filteredFormLable[key],
            text: texts.join(','),
            key,
          })
        } else if (key == 'operateTimeBegin' && this.filterForm[key]) {
          list.push({
            title: this.filteredFormLable[key],
            text: `${moment(this.filterForm['operateTimeBegin']).format('YYYY-MM-DD')}~${moment(
              this.filterForm['operateTimeEnd']
            ).format('YYYY-MM-DD')}`,
            key,
          })
        } else if (key == 'operateTimeEnd' && this.filterForm[key]) {
        } else {
          list.push({
            title: this.filteredFormLable[key],
            text: this.filterForm[key],
            key,
          })
        }
      }
      return list
    },
  },
  methods: {
    changeSelect(v, key) {
      if (v.length == 0) {
        this.filterForm[key] = undefined
      }
    },
    /* 时间选择 */
    onOk(value, key) {
      if (value.length == 0) {
        this.filterForm[`${key}Begin`] = ''
        this.filterForm[`${key}End`] = ''
        return
      }
      this.filterForm[`${key}Begin`] = moment(value[0]).startOf('day').format('YYYY-MM-DD HH:mm:ss')
      this.filterForm[`${key}End`] = moment(value[1]).endOf('day').format('YYYY-MM-DD HH:mm:ss')
    },
    // 获取筛选列表
    getList(v) {
      return this[v] ? this[v] : []
    },
    showModal(v, Entity) {
      this.Entity = `busi_${Entity}_SETTING`
      this.batchInfo = v
      console.log(v,'vvvv');
      let today = moment().format('YYYY-MM-DD HH:mm')
      this.fullName = `${v.batchCode}（生产批次记录${today}）`
      this.visible = true
      this.initData()
      // requestId查批次记录
    },
    // 列表初始配置
    initData() {
      /* 设置列 */
      var oldValue = localStorage.getItem(this.Entity)
      this.columns = getNewColumns(columnsValue, JSON.parse(oldValue), [], this.columns)
      getTaskOptionList({ orderId: this.batchInfo.orderId }).then((res) => {
        this.taskList = res.result || []
      })
      getDeviceListByBatchId({ batchId: this.batchInfo.id }).then((res) => {
        this.deviceList = res.result || []
      })
      getOperatorListByBatchId({ batchId: this.batchInfo.id }).then((res) => {
        this.operatorList = res.result || []
      })
      getTeamGroupByBatchId({ batchId: this.batchInfo.id }).then((res) => {
        this.teamList = res.result || []
      })
      this.requestData()
    },
    propForm() {
      let params = {
        batchId: this.batchInfo.id,
        ...this.filterForm,
        pageNo: this.current,
        pageSize: this.pageSize,
      }
      for (let key in params) {
        if (!params[key]) {
          delete params[key]
        }
        if (params[key]) {
          if (
            key == 'operateType' ||
            key == 'taskId' ||
            key == 'deviceId' ||
            key == 'operatorId' ||
            key == 'teamGroupId'
          ) {
            params[key] = params[key].join(',')
          }
        }
      }
      return params
    },
    requestData() {
      this.loadingTable = true
      let params = {
        batchId: this.batchInfo.id,
        ...this.filterForm,
        ...this.sortForm,
        pageNo: this.current,
        pageSize: this.pageSize,
      }
      for (let key in params) {
        if (!params[key]) {
          delete params[key]
        }
        if (params[key]) {
          if (
            key == 'operateType' ||
            key == 'taskId' ||
            key == 'deviceId' ||
            key == 'operatorId' ||
            key == 'teamGroupId'
          ) {
            params[key] = params[key].join(',')
          }
        }
      }
      queryProduceRecord(params).then((res) => {
        if (res.code == 200) {
          this.dataSource = res.result.records
          this.total = res.result.total
        }
        this.loadingTable = false
      })
    },
    handleCancel() {
      this.visible = false
      // 重置筛选
    },
    // 分页
    onChangePage(current, pageSize) {
      this.pageSize = pageSize
      this.current = current
      this.requestData()
    },
    handleSearch(selectedKeys, confirm, dataIndex, clearFilters) {
      this.current = 1
      this.requestData()
    },
    /* 打开筛选 */
    handleShowFilter() {
      this.showFilter = true
    },
    /* 关闭筛选 */
    closeFilter() {
      this.showFilter = false
    },
    /* 确定筛选 */
    handleFilter() {
      this.handleSearch()
      this.showFilter = false
    },
    /* 删除已选 */
    delFiltered(key) {
      if (key == 'operateType' || key == 'taskId' || key == 'deviceId' || key == 'operatorId' || key == 'teamGroupId') {
        this.filterForm[key] = undefined
      } else {
        this.filterForm[key] = ''
        this.filterForm['operateTimeEnd'] = ''
        this.dateForm = {}
      }
    },
    /* 重置筛选 */
    resetFilter() {
      this.filterForm = {
        operateTimeBegin: '',
        operateTimeEnd: '',
        operateType: undefined,
        taskId: undefined,
        deviceId: undefined,
        operatorId: undefined,
        teamGroupId: undefined,
      }
      this.dateForm = {}
      this.handleSearch()
    },
    showColumn() {
      this.showSetColumn = true
      this.$nextTick(() => {
        this.$refs.SetColumn.paramsData(columnsValue, this.Entity, this.columns, true)
      })
    },
    sureBtn(emitArr) {
      this.columns = getNewColumns(columnsValue, emitArr, [])
      localStorage.setItem(this.Entity, JSON.stringify(emitArr))
      this.tableKey += 1
    },
    // table
    tableChange(pagination, filters, sorter, { currentDataSource }) {
      if (sorter.order) {
        let sortType = ''
        if (sorter.order == 'ascend') {
          sortType = 'ASC'
        } else {
          sortType = 'DESC'
        }
        this.sortForm = {
          sortType: sortType,
          sortColumn: sorter.columnKey,
        }
        this.requestData()
      } else {
        this.sortForm = {
          sortType: '',
          sortColumn: '',
        }
        this.requestData()
      }
    },
  },
}
</script>
<style lang="less" scoped>
@import '~@/assets/less/public.less';
.flex(@jc,@ai,@fd:row) {
  display: flex;
  justify-content: @jc;
  align-items: @ai;
  flex-direction: @fd;
}
.searchWorkOreder {
  .flex(flex-start, center);
  padding: 8px;
}
.topBox {
  .flex(space-between, center);
  margin-bottom: 16px;
}
.filter-tit {
  background: #fff;
  border-bottom: 1px solid @greyBorder;
  font-size: @fontSize4;
}
.filter-num {
  color: @normalFont;
}
.filter-body {
  height: calc(100vh - 160px);
  display: flex;
  flex-direction: column;
}
.margin-btn {
  margin-right: @distance5;
}
.filter-tag {
  display: inline-block;
  position: relative;
  padding: 8px 10px;
  border-radius: 4px;
  font-size: @fontSize1;
  line-height: @fontSize1;
  max-width: 100%;
  background: @greyBg;
  color: @titFont;
  cursor: pointer;
  .tag-text {
    display: inline-block;
    padding-right: 20px;
    max-width: 100%;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
  .anticon-close {
    position: absolute;
    right: 8px;
    top: 8px;
  }
}
.tag-wrap:nth-of-type(n + 2) {
  margin-top: 10px;
}
</style>
